package com.wangdao.wechatmall.controller.wx;

import com.wangdao.wechatmall.bean.bo.wx.*;
import com.wangdao.wechatmall.bean.pojo.User;
import com.wangdao.wechatmall.bean.pojo.UserExample;
import com.wangdao.wechatmall.bean.vo.admin.BaseRespVo;
import com.wangdao.wechatmall.bean.vo.wx.CartIndexVo;
import com.wangdao.wechatmall.bean.vo.wx.WXCartCheckOutVO;
import com.wangdao.wechatmall.bean.bo.wx.WXCartCheckedBO;
import com.wangdao.wechatmall.bean.bo.wx.WXCartDeleteBO;
import com.wangdao.wechatmall.bean.bo.wx.WXCartUpdateBO;
import com.wangdao.wechatmall.bean.vo.wx.WXBaseRespVo;
import com.wangdao.wechatmall.bean.vo.wx.WXCartIndexVO;
import com.wangdao.wechatmall.exception.CouponUnusbaleException;
import com.wangdao.wechatmall.mapper.UserMapper;
import com.wangdao.wechatmall.service.wx.WXCartService;
import com.wangdao.wechatmall.util.WXSystemUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @ClassName: WXCartController
 * @Description 购物车
 * @Author Xinhao Yi
 * @Date 2021/7/11  21:08
 */
@RestController
@RequestMapping("wx/cart")
public class WXCartController {

    @Autowired
    WXCartService wxCartService;

    @Autowired
    UserMapper userMapper;

    //Request URL: http://localhost:8083/wx/cart/index
    //响应负载：{"cartTotal":{"goodsCount":7,"checkedGoodsCount":7,"goodsAmount":591.00,"checkedGoodsAmount":591.00},"cartList":[{"id":89,"userId":1,"goodsId":1181054,"goodsSn":"11","goodsName":"22","productId":457,"price":11.00,"number":2,"specifications":["标准","撒"],"checked":true,"picUrl":"http://182.92.235.201:8083/wx/storage/fetch/vgvffi3250gkajhq29j4.gif","addTime":"2021-07-11 19:37:01","updateTime":"2021-07-11 20:34:34","deleted":false},{"id":91,"userId":1,"goodsId":1181048,"goodsSn":"222","goodsName":"测试手机","productId":399,"price":200.00,"number":2,"specifications":["标准","红色"],"checked":true,"picUrl":"http://182.92.235.201:8083/wx/storage/fetch/dy5z5f90yo6m9oul2tz8.png","addTime":"2021-07-11 20:15:20","updateTime":"2021-07-11 20:28:49","deleted":false},{"id":92,"userId":1,"goodsId":1039051,"goodsSn":"1039051","goodsName":"多功能午睡枕","productId":54,"price":79.00,"number":2,"specifications":["标准"],"checked":true,"picUrl":"http://yanxuan.nosdn.127.net/c8ca0600fa7ba11ca8be6a3173dd38c9.png","addTime":"2021-07-11 20:23:16","updateTime":"2021-07-11 20:28:50","deleted":false},{"id":93,"userId":1,"goodsId":1181013,"goodsSn":"55","goodsName":"猫","productId":275,"price":11.00,"number":1,"specifications":["标准"],"checked":true,"picUrl":"http://182.92.235.201:8083/wx/storage/fetch/1dwn7di7ox33mq28af07.jpeg","addTime":"2021-07-11 20:40:13","updateTime":"2021-07-11 20:40:13","deleted":false}]}
    /**
     * 拿取购物车的相关信息，形成页面
     * @return
     */
    @GetMapping("/index")
    public WXBaseRespVo index() {
        WXCartIndexVO wxCartIndexVO = wxCartService.list(false);
        return WXBaseRespVo.ok(wxCartIndexVO);
    }



    //Request URL: http://182.92.235.201:8083/wx/cart/add
    //响应负载：{"goodsId":1128010,"number":1,"productId":441}
    //响应报文：{"errno":0,"data":7,"errmsg":"成功"}
    /**
     * 往购物车里增加商品
     */
    @PostMapping("/add")
    public WXBaseRespVo add(@RequestBody WXCartAddBO param){
        Integer add = wxCartService.add(param,false);
        if (add == 0){
            //查找该用户购物车里的商品总数量
            Integer totalNum = wxCartService.countTotalGoodsNum();
            //要返回
            return WXBaseRespVo.ok(totalNum,"成功");
        }
        else if (add == -1){
            return WXBaseRespVo.fail("库存不够");
        }
        else {
            return WXBaseRespVo.fail("系统维护中");
        }
    }

    //Request URL: http://182.92.235.201:8083/wx/cart/fastadd
    //请求载体：{"goodsId":1181047,"number":1,"productId":443}
    //响应载体：{"errno":0,"data":290,"errmsg":"成功"}
    /**
     * 快速添加到购物车
     */
    @PostMapping("/fastadd")
    //事务回滚
    @Transactional(rollbackFor = Exception.class)
    public WXBaseRespVo fastadd(@RequestBody WXCartAddBO param){
        Integer firstAdd = wxCartService.add(param,true);
        if (firstAdd == -1){
            return WXBaseRespVo.fail("库存不够");
        }
        else if (firstAdd == -2){
            return WXBaseRespVo.fail("系统维护中");
        }
        else {
            return WXBaseRespVo.ok(firstAdd);
        }
    }

    //Request URL: http://localhost:8083/wx/cart/checkout?cartId=0&addressId=0&couponId=0&grouponRulesId=0
    //请求负载：cartId=298&addressId=0&couponId=0&grouponRulesId=0
    //响应负载：{"errno":0,"data":{"grouponPrice":0,"grouponRulesId":0,"checkedAddress":{"id":0},"actualPrice":530.00,"orderTotalPrice":530.00,"couponPrice":70.00,"availableCouponLength":25,"couponId":81,"freightPrice":0,"checkedGoodsList":[{"id":298,"userId":1,"goodsId":1181048,"goodsSn":"222","goodsName":"测试手机","productId":400,"price":300.00,"number":2,"specifications":["高端","红色"],"checked":true,"picUrl":"http://182.92.235.201:8083/wx/storage/fetch/dy5z5f90yo6m9oul2tz8.png","addTime":"2021-07-12 20:08:51","updateTime":"2021-07-12 20:09:14","deleted":false}],"goodsTotalPrice":600.00,"addressId":0},"errmsg":"成功"}

    @GetMapping("/checkout")
    public WXBaseRespVo checkout(WXCartCheckOutBO param){
//        //只查找选中的
//        WXCartIndexVO wxCartIndexVO = wxCartService.list(true);
//        //如果是fastAdd的话，cartId会是一个大于0的数，如果是正常购买的话，cartId会为0
//        //咱们要把fastAdd加进来的数据伪删除掉，不让它在购物车里面显示
//        if (param.getCartId() > 0){
//            //同时，我们需要的wxCartIndexVO，也不是上面那个，而是单独只有这个fastAdd进去的cart的数据
//            WXCartCheckOutVO wxCartCheckOutVO = null;
//            try{
//            wxCartIndexVO = wxCartService.list(param.getCartId(),true);
//            //组装出fastAdd的结果
//            wxCartCheckOutVO = wxCartService.getCheckOutVO(param,wxCartIndexVO);
//            //删掉fastAdd的记录，因为它已经出购物车了，也就是买完了
//            wxCartService.removeCartByCartId(param.getCartId());
//            }
//            catch (Exception e){
//                e.printStackTrace();
//            }
//            return WXBaseRespVo.ok(wxCartCheckOutVO);
//        }
//        //不是firstAdd的话，cartId会为0
//        //组装出结果
//        WXCartCheckOutVO wxCartCheckOutVO = wxCartService.getCheckOutVO(param,wxCartIndexVO);
//        return WXBaseRespVo.ok(wxCartCheckOutVO);


        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipals().getPrimaryPrincipal();
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<User> users = userMapper.selectByExample(userExample);
        User user = users.get(0);

        Integer userID = user.getId();
        WXCartIndexVO cartCheckedList = wxCartService.queryCartIndex(userID, param.getCartId(), true);

        if (param.getCartId()>0){//快速下单的情况，不应在cart中维护其记录，所以要删除，不能让其出现在购物车中
            wxCartService.removeCartByCartId(param.getCartId());
        }
        WXCartCheckOutVO cartCheckoutVo = wxCartService.queryCartCheckoutInfo(userID, param, cartCheckedList);

        return WXBaseRespVo.ok(cartCheckoutVo);

    }



    //Request URL: http://182.92.235.201:8083/wx/cart/goodscount
    //请求载体：
    //响应载体：{"errno":0,"data":1,"errmsg":"成功"}
    /**
     * 查找该用户购物车里的商品总数量
     */
    @GetMapping("/goodscount")
    public WXBaseRespVo goodscount(){
        Integer totalNum = wxCartService.countTotalCartsNum();
        return WXBaseRespVo.ok(totalNum,"成功");
    }

    //Request URL: http://localhost:8083/wx/cart/checked
    //请求负载：{"productIds":[457,441],"isChecked":1}
    //请求负载：{"productIds":[457,441],"isChecked":0}
    //响应负载：{"cartTotal":{"goodsCount":8,"checkedGoodsCount":8,"goodsAmount":77.50,"checkedGoodsAmount":77.50},"cartList":[{"id":108,"userId":1,"goodsId":1181071,"goodsSn":"s","goodsName":"优惠券检验","productId":477,"price":0.50,"number":1,"specifications":["标准"],"checked":true,"picUrl":"http://182.92.235.201:8083/wx/storage/fetch/49ugir5n16q9gztduiuz.jpg","addTime":"2021-07-11 21:48:42","updateTime":"2021-07-11 21:51:50","deleted":false},{"id":109,"userId":1,"goodsId":1181054,"goodsSn":"11","goodsName":"22","productId":457,"price":11.00,"number":7,"specifications":["标准","撒"],"checked":true,"picUrl":"http://182.92.235.201:8083/wx/storage/fetch/vgvffi3250gkajhq29j4.gif","addTime":"2021-07-11 21:50:01","updateTime":"2021-07-11 21:51:50","deleted":false}]}
    /**
     * 改变选中状态，isChecked为1为选中，为0为不选中
     * @return
     */
    @PostMapping("/checked")
    public WXBaseRespVo checked(@RequestBody WXCartCheckedBO param) {
        Boolean isChecked = wxCartService.checked(param);
        //再查找一次
        WXCartIndexVO list = wxCartService.list(false);
        //true修改成功
        if (isChecked) {
            return WXBaseRespVo.ok(list);
        }
        //修改失败
        else {
            return WXBaseRespVo.ok(list,"失败，无法选中！");
        }


    }



    //Request URL: http://182.92.235.201:8083/wx/cart/update
    //请求负载：{"productId":457,"goodsId":1181054,"number":2,"id":111}
    //响应负载：{"errno":0,"errmsg":"成功"}
    /**
     * 编辑购物车里的内容，点一下 + 或者 - 就会触发update，增加购物车里product的数量
     * @return
     */
    @PostMapping("/update")
    public WXBaseRespVo update(@RequestBody WXCartUpdateBO param) {
        Integer isUpadate = wxCartService.update(param);
        if (isUpadate == 404){
            return WXBaseRespVo.fail("编辑失败，库存不足");
        }
        else if (isUpadate == 405){
            return WXBaseRespVo.fail("编辑失败，其他异常");
        }
        //200
        else {
            return WXBaseRespVo.ok("编辑成功");
        }
    }


    //Request URL: http://182.92.235.201:8083/wx/cart/delete
    //请求负载：{"productIds":[441,54]}
    //响应负载：{"cartTotal":{"goodsCount":102,"checkedGoodsCount":1,"goodsAmount":30010.00,"checkedGoodsAmount":9999.00},"cartList":[{"id":111,"userId":1,"goodsId":1181054,"goodsSn":"11","goodsName":"22","productId":457,"price":11.00,"number":1,"specifications":["标准","撒"],"checked":false,"picUrl":"http://182.92.235.201:8083/wx/storage/fetch/vgvffi3250gkajhq29j4.gif","addTime":"2021-07-11 22:12:20","updateTime":"2021-07-11 22:32:28","deleted":false},{"id":113,"userId":1,"goodsId":1181048,"goodsSn":"222","goodsName":"测试手机","productId":399,"price":200.00,"number":100,"specifications":["标准","红色"],"checked":false,"picUrl":"http://182.92.235.201:8083/wx/storage/fetch/dy5z5f90yo6m9oul2tz8.png","addTime":"2021-07-11 22:23:13","updateTime":"2021-07-11 22:31:35","deleted":false},{"id":115,"userId":1,"goodsId":1181044,"goodsSn":"865627694","goodsName":"封寒月","productId":452,"price":9999.00,"number":1,"specifications":["六星"],"checked":true,"picUrl":"http://182.92.235.201:8083/wx/storage/fetch/7k4cwa89w6c396vjn175.jpg","addTime":"2021-07-11 22:29:44","updateTime":"2021-07-11 22:29:44","deleted":false}]}

    /**
     * 删除购物车中的内容，直接响应给前端
     * @return
     */
    @PostMapping("/delete")
    public WXBaseRespVo delete(@RequestBody WXCartDeleteBO param) {
        Integer delete = wxCartService.delete(param);
        if (delete == 404){
            return WXBaseRespVo.fail("删除失败");
        }
        //200
        else {
            //再查找一次
            WXCartIndexVO list = wxCartService.list(false);
            return WXBaseRespVo.ok(list,"删除成功");
        }
    }



}
